//创建用户相关仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user/userApi'
import type { loginForm, loginRespData, userInfoResp } from '@/api/user/type'
import type { UserState } from './types/type'
import { GET_TOKEN, SET_TOKEN, CLEAR_TOKEN } from '@/utils/token'
import { constRoutes } from '@/router/routes'

export const useUserStore = defineStore('user', {
  state(): UserState {
    return {
      token: GET_TOKEN() || '',
      menuRoutes: constRoutes,
      userName: '',
      avatar: '',
    }
  },
  getters: {},
  actions: {
    //用户登录方法
    async userLogin(data: loginForm) {
      let resp: loginRespData = await reqLogin(data)
      if (resp.code === 200) {
        this.token = resp.data!.token
        SET_TOKEN(resp.data!.token)
        return resp
      } else {
        return Promise.reject(new Error(resp.message))
      }
    },
    //获取用户信息方法
    async userInfo() {
      //获取用户信息进行仓库存储[用户头像、名字]
      let resp: userInfoResp = await reqUserInfo()
      if (resp.code === 200) {
        this.userName = resp.data.userName
        this.avatar = resp.data.avatar
      } else {
        return Promise.reject(new Error(resp.message))
      }
    },
    //退出登录，清除用户信息
    userLogout() {
      //1.请求后端
      //2.清除本地用户信息
      this.token = ''
      // this.menuRoutes = []
      this.userName = ''
      this.avatar = ''
      CLEAR_TOKEN()
    },
  },
})
